package com.springboot.cloud.demos.ribbon.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.exception.SystemErrorType;
import com.springboot.cloud.demos.entity.form.AppVersionForm;
import com.springboot.cloud.demos.entity.po.AppVersion;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class AppVersionService {

    @Autowired
    RestTemplate restTemplate;

    @SentinelResource(fallback = "lastFallback")
    public Result last(String platform) {
        return restTemplate.getForEntity("http://producer/appVersion/last?platform={1}", Result.class, platform).getBody();
    }

    public Result lastFallback() {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }


    @SentinelResource(fallback = "conditionsFallback")
    public Result list() {
        return restTemplate.getForEntity("http://producer/appVersion", Result.class).getBody();
    }

    public Result conditionsFallback() {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "appVersionFallback")
    public Result appVersion(String appVersionId) {
        return restTemplate.getForEntity("http://producer/appVersion/{appVersionId}", Result.class, appVersionId).getBody();
    }

    public Result appVersionFallback(@RequestBody Map params) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "saveFallback")
    public Result save(@RequestBody AppVersionForm appVersionForm) {
        return restTemplate.postForEntity("http://producer/appVersion", appVersionForm, Result.class).getBody();
    }

    @SentinelResource(fallback = "updateFallback")
    public Result update(@RequestBody AppVersionForm appVersionForm) {
        restTemplate.put("http://producer/appVersion/{1}", appVersionForm, appVersionForm.getId());
        return Result.success();
    }

    public Result saveFallback(@RequestBody AppVersionForm appVersionForm) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result updateFallback(AppVersion appVersion) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "updateFallback")
    public Result delete(String appVersionId) {
        restTemplate.delete("http://producer/appVersion/{1}", appVersionId);
        return Result.success();
    }
}
